package com.huafv.flyauth.security;

import com.huafv.flyauth.web.admin.entity.SysUser;
import com.huafv.flyauth.web.admin.service.SysMenuService;
import com.huafv.flyauth.web.admin.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    SysMenuService sysMenuService;

    // 实现UserDetailsService接口，重写UserDetails方法，自定义用户的信息从数据中查询
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //（认证，即校验该用户是否存在）查询用户信息
        SysUser sysUser = sysUserService.getByUsername(username);

        //如果没有查询到用户
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("用户名或者密码错误");
        }

        // 授权，即查询用户具有哪些权限)查询对应的用户信息
        List<String> perms = sysMenuService.getPermsByUserId(sysUser.getId());

        //定义一个权限集合
        List<String> list = new ArrayList<>(Arrays.asList("test", "admin"));


        //把数据封装成UserDetails返回
        return new LoginUser(sysUser, perms);
    }
}